package com.kaizeli.website.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaizeli.website.mapper.AcceptanceMemberMapper;
import com.kaizeli.website.pojo.entity.AcceptanceMember;
import com.kaizeli.website.pojo.dto.AcceptanceMemberDTO;
import com.kaizeli.website.service.AcceptanceMemberService;
import com.kaizeli.website.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 验收成员服务实现类
 */
@Service
public class AcceptanceMemberServiceImpl extends ServiceImpl<AcceptanceMemberMapper, AcceptanceMember> implements AcceptanceMemberService {

    @Autowired
    private AcceptanceMemberMapper acceptanceMemberMapper;

    @Autowired
    private com.kaizeli.website.service.ProjectAcceptanceService projectAcceptanceService;

    @Override
    public Result<List<AcceptanceMemberDTO>> getMembersByAcceptanceId(Long acceptanceId) {
        try {
            List<AcceptanceMemberDTO> members = acceptanceMemberMapper.selectByAcceptanceId(acceptanceId);
            return Result.success(members);
        } catch (Exception e) {
            return Result.error(500, "查询验收成员失败：" + e.getMessage());
        }
    }

    @Override
    public Result<List<AcceptanceMemberDTO>> getMembersByEmployeeId(Long employeeId) {
        try {
            List<AcceptanceMemberDTO> members = acceptanceMemberMapper.selectByEmployeeId(employeeId);
            return Result.success(members);
        } catch (Exception e) {
            return Result.error(500, "查询验收记录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<AcceptanceMember> createMember(AcceptanceMember member) {
        try {
            member.setCreateTime(LocalDateTime.now());
            member.setUpdateTime(LocalDateTime.now());
            member.setStatus("待验收");
            
            // 计算结算金额
            calculateSettlementAmount(member);
            
            save(member);
            
            // 更新验收单的总工时
            if (member.getAcceptanceId() != null) {
                updateAcceptanceTotalHours((long) member.getAcceptanceId());
            }
            
            return Result.success(member);
        } catch (Exception e) {
            return Result.error(500, "创建验收成员失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> batchCreateMembers(List<AcceptanceMember> members) {
        try {
            Integer acceptanceId = null;
            for (AcceptanceMember member : members) {
                member.setCreateTime(LocalDateTime.now());
                member.setUpdateTime(LocalDateTime.now());
                member.setStatus("待验收");
                
                // 计算结算金额
                calculateSettlementAmount(member);
                
                // 记录验收单ID用于后续更新总工时
                if (member.getAcceptanceId() != null) {
                    acceptanceId = member.getAcceptanceId();
                }
            }
            
            int result = acceptanceMemberMapper.batchInsert(members);
            if (result > 0) {
                // 更新验收单的总工时
                if (acceptanceId != null) {
                    updateAcceptanceTotalHours((long) acceptanceId);
                }
                return Result.success();
            } else {
                return Result.error(500, "批量创建验收成员失败");
            }
        } catch (Exception e) {
            return Result.error(500, "批量创建验收成员失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateMember(Long id, AcceptanceMember member) {
        try {
            Integer memberId = id.intValue();
            AcceptanceMember existingMember = getById(memberId);
            if (existingMember == null) {
                return Result.error(404, "验收成员不存在");
            }
            
            member.setId(memberId);
            
            // 重新计算结算金额
            calculateSettlementAmount(member);
            
            updateById(member);
            
            // 更新验收单的总工时
            if (member.getAcceptanceId() != null) {
                updateAcceptanceTotalHours((long) member.getAcceptanceId());
            }
            
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "更新验收成员失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> updateMemberStatus(Long id, String status) {
        try {
            int result = acceptanceMemberMapper.updateStatus(id, status);
            if (result > 0) {
                return Result.success();
            } else {
                return Result.error(404, "验收成员不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "更新验收成员状态失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> deleteMember(Long id) {
        try {
            // 先获取成员信息以便后续更新验收单总工时
            AcceptanceMember member = getById(id.intValue());
            Integer acceptanceId = member != null ? member.getAcceptanceId() : null;
            
            boolean result = removeById(id.intValue());
            if (result) {
                // 更新验收单的总工时
                if (acceptanceId != null) {
                    updateAcceptanceTotalHours((long) acceptanceId);
                }
                return Result.success();
            } else {
                return Result.error(404, "验收成员不存在");
            }
        } catch (Exception e) {
            return Result.error(500, "删除验收成员失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result<Void> transferMember(Long id, String newProjectCode, Long newSubProjectId) {
        try {
            AcceptanceMember member = getById(id.intValue());
            if (member == null) {
                return Result.error(404, "验收成员不存在");
            }
            
            // TODO: 查找新项目的验收单，如果没有则创建
            // 这里需要根据项目编号和子项目ID查找验收单
            // 如果不存在，需要创建新的验收单
            
            // 暂时更新成员信息
            // member.setAcceptanceId(newAcceptanceId);
            // 这里还需要更新其他相关信息
            
            updateById(member);
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "转项失败：" + e.getMessage());
        }
    }

    /**
     * 计算结算金额
     */
    private void calculateSettlementAmount(AcceptanceMember member) {
        if (member.getUnitPrice() != null && member.getActualHours() != null) {
            BigDecimal settlementAmount = member.getUnitPrice().multiply(member.getActualHours());
            member.setSettlementAmount(settlementAmount);
        } else if (member.getUnitPrice() != null && member.getEstimatedHours() != null) {
            BigDecimal settlementAmount = member.getUnitPrice().multiply(member.getEstimatedHours());
            member.setSettlementAmount(settlementAmount);
        } else {
            member.setSettlementAmount(BigDecimal.ZERO);
        }
    }

    /**
     * 更新验收单的总工时
     */
    private void updateAcceptanceTotalHours(Long acceptanceId) {
        try {
            // 查询所有成员的实际工时
            List<AcceptanceMemberDTO> members = acceptanceMemberMapper.selectByAcceptanceId(acceptanceId);
            
            // 计算总工时
            BigDecimal totalHours = members.stream()
                    .map(member -> member.getActualHours() != null ? member.getActualHours() : BigDecimal.ZERO)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            // 更新验收单的总工时
            com.kaizeli.website.pojo.entity.ProjectAcceptance acceptance = 
                    projectAcceptanceService.getById(acceptanceId.intValue());
            if (acceptance != null) {
                acceptance.setTotalHours(totalHours);
                projectAcceptanceService.updateById(acceptance);
            }
        } catch (Exception e) {
            // 记录错误但不抛出异常，避免影响主要业务逻辑
            e.printStackTrace();
        }
    }
}
